/*
 * @Author: hongbin
 * @Date: 2022-03-28 12:10:04
 * @LastEditors: hongbin
 * @LastEditTime: 2022-04-06 18:26:48
 * @Description:ElementContext
 */

import { createContext, FC, ReactElement, useCallback, useContext, useEffect, useState } from "react";
import { ElementNode } from "../components/ElementProvider/ElementList";
import { unitToPx } from "../utils";

type SetState<T> = React.Dispatch<React.SetStateAction<T>>;

export interface IContext {
  /**
   * 当前拖拽的元素
   */
  current: ElementNode | null;
  /**
   * 设置当前拖拽的元素
   */
  setCurrent: SetState<IContext["current"]>;
  /**
   * 预览区域的坐标
   */
  pageAxis: typeof defaultLayout;
  /**
   * 设置预览区域坐标
   */
  setPageAxis: SetState<IContext["pageAxis"]>;
  /**
   * 元素树 生成页面节点
   */
  elementTree: ElementNode[];
  setElementTree: SetState<IContext["elementTree"]>;
  deleteElementNode: (key: ElementNode["key"]) => void;
  axisPosition: { top: number; left: number };
}

const Context = createContext<IContext>({} as any);

const defaultLayout = {
  minX: 0,
  minY: 0,
  maxX: 0,
  maxY: 0,
  width: 0,
  height: 0,
};

const handleSome = (key: string, select: boolean) => (node: ElementNode) => {
  if (node.key === key) {
    if (select) {
      node.style["border"] = "1px solid #000";
    } else {
      delete node.style["border"];
    }
    return true;
  }
  return false;
};

const ElementContext: FC = ({ children }): ReactElement => {
  const [current, setCurrent] = useState<ElementNode | null>(null);
  const [pageAxis, setPageAxis] = useState(defaultLayout);
  const [axisPosition, setAxisPosition] = useState({ top: -200, left: -200 });
  const [elementTree, setElementTree] = useState<ElementNode[]>([]);
  console.log(elementTree);

  const deleteElementNode = useCallback((key: ElementNode["key"]) => {
    setElementTree((prev) => prev.filter((node) => node.key !== key));
  }, []);

  useEffect(() => {
    if (!current) return;
    console.log("newCurrent:", current);
    // setElementNodeSelect(current.key, true);
    const { top, left, height, width } = current.style;

    setAxisPosition({
      top: unitToPx(top, current.unit["top"]) + (unitToPx(height, current.unit["height"]) * window.scaleMultiple) / 2,
      left: unitToPx(left, current.unit["left"]) + (unitToPx(width, current.unit["width"]) * window.scaleMultiple) / 2,
    });
    // return () => setElementNodeSelect(current.key, false);
  }, [current]);

  return (
    <Context.Provider
      value={{
        current,
        setCurrent,
        pageAxis,
        setPageAxis,
        elementTree,
        setElementTree,
        deleteElementNode,
        axisPosition,
      }}
    >
      {children}
    </Context.Provider>
  );
};

export default ElementContext;

export const useElementContext = () => useContext(Context);
